# ==== alu.py ====
class ALU:
    @staticmethod
    def execute(op, operand1, operand2):
        # 确保32位整数
        op1 = operand1 & 0xFFFFFFFF
        op2 = operand2 & 0xFFFFFFFF

        # 转换为有符号整数（32位补码）
        def to_signed(x):
            x = x & 0xFFFFFFFF
            return x if x < 0x80000000 else x - 0x100000000

        op1_signed = to_signed(op1)
        op2_signed = to_signed(op2)

        # 调试输出
        print(f"ALU执行: op={op}, op1={op1}({to_signed(op1)}), op2={op2}({to_signed(op2)})")

        result = 0
        zero = False

        if op == "ADD":
            result = op1_signed + op2_signed
        elif op == "SUB":
            # 特别注意减法顺序
            result = op1_signed - op2_signed
            print(f"减法: {op1_signed} - {op2_signed} = {result}")
        elif op == "AND":
            result = op1 & op2
        elif op == "OR":
            result = op1 | op2
        elif op == "SLT":
            result = 1 if op1_signed < op2_signed else 0
        else:
            result = op1_signed + op2_signed

        # 将结果转换回32位无符号表示
        unsigned_result = result & 0xFFFFFFFF
        # 处理负数情况
        if result < 0:
            unsigned_result = (1 << 32) + result

        # 零标志设置
        zero = (unsigned_result == 0)

        # 调试输出
        print(f"结果: {result}, 无符号表示: {unsigned_result}, 零标志: {zero}")

        return unsigned_result, zero